package cn.shop.front.controller.wx.utils;

import cn.shop.front.controller.wx.WxTemplateMsg;
import com.alibaba.fastjson.JSONObject;

import java.util.TreeMap;

public class WxUtils {

    public static String noticeTemplate(String templateId, String appId, String secret, String openId) {
        // 模版ID
        TreeMap<String, TreeMap<String, String>> params = new TreeMap<>();
        //根据具体模板参数组装
        params.put("first", WxTemplateMsg.item("您的账号已在Q视界登录。", "#000000"));
        params.put("keyword1", WxTemplateMsg.item("紫红0802", "#000000"));
        params.put("keyword2", WxTemplateMsg.item("2018-09-04 12:22", "#000000"));
        params.put("keyword3", WxTemplateMsg.item("HUAWEI", "#000000"));
        params.put("remark", WxTemplateMsg.item("感谢您使用Q视界。", "#000000"));
        WxTemplateMsg wxTemplateMsg = new WxTemplateMsg();
        // 模版ID
        wxTemplateMsg.setTemplate_id(templateId);
        // openId
        //我的openId: oaCNj6FuO1Jr_a2u9Q79i2dif8-0
        wxTemplateMsg.setTouser(openId);
        // 关键字赋值
        wxTemplateMsg.setData(params);
        String data = JsonUtils.ObjectToString(wxTemplateMsg);
        return handleSendMsgLog(data, appId, secret);
    }

    private static String handleSendMsgLog(String data, String appId, String secret) {
        try {
            return sendTemplateMsg(data, appId, secret);
        } catch (Exception exception) {
            System.out.println("发送模版失败");
        }
        return null;
    }


    public static String sendTemplateMsg(String data,String appId, String secret) throws Exception {
        // 获取token
        String accessToken = getAccessToken(appId, secret);
        // 发送消息
        //HttpResult httpResult = HttpUtils.stringPostJson(Constants.SEND_MESSAGE_TEMPLATE_URL + accessToken, data);
        //return IMJsonUtils.getObject(httpResult.getBody(), TemplateMsgResultDto.class);

        String result = HttpUtils.sendPost(Constants.SEND_MESSAGE_TEMPLATE_URL + accessToken, data);
        return result;
    }


    /**
     * 获取全局token
     */
    public static String getAccessToken(String appId, String secret) {
        String params = "grant_type=client_credential" +
                "&secret=" + secret +
                "&appid="+ appId;
        //发送GET请求
        String result = HttpUtils.sendGet("https://api.weixin.qq.com/cgi-bin/token", params);
        System.out.println(result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        System.out.println(jsonObject);
        return jsonObject.getString("access_token");
    }


}
